<template>
  <div id="orderPage">
    <!-- 顶部筛选搜索bar -->
    <div id="topBar">
      <el-input
        style="flex: 1; margin-right: 1rem; max-width: 30%"
        v-model="searchData.pickup_number"
        placeholder="请输入取餐码"
        clearable
      ></el-input>
      <div class="topBarSwitch">
        <span>{{ searchData.status ? "完成" : "未完成" }}</span>
        <el-switch v-model="searchData.status" />
      </div>
      <div class="topBarSwitch">
        <span>{{ searchData.takeoutOrNot ? "外卖" : "自取" }}</span>
        <el-switch v-model="searchData.takeoutOrNot" />
      </div>
      <el-date-picker
        v-model="searchData.time"
        type="date"
        placeholder="请选择下单日期"
        value-format="YYYY-MM-DD"
        style="margin-right: 1rem"
      ></el-date-picker>
      <el-tooltip effect="dark" placement="bottom" content="搜索">
        <el-button :icon="Search" @click="search(true)" circle />
      </el-tooltip>
      <el-tooltip effect="dark" placement="bottom" content="清空">
        <el-button :icon="Close" @click="cleanCondition" circle />
      </el-tooltip>
    </div>
    <!-- 表格 -->
    <el-table :data="orderData" style="width: 90%; margin: 0 auto">
      <el-table-column label="取餐号" fixed="left" align="center">
        <template #default="scope">
          {{ "B" + scope.row.pickup_number }}
        </template>
      </el-table-column>
      <el-table-column label="订单内容" align="center" fixed="left">
        <template #default="scope">
          <el-card
            v-for="item in scope.row.content"
            :key="item.id"
            :body-style="{ padding: '1rem' }"
          >
            <template #header>
              <div class="card-header">
                <span>{{ item.goodData.name }}</span>
                <span>x {{ item.count }} </span>
              </div>
            </template>
            <el-tag
              type="info"
              style="cursor: pointer; margin: 0.3rem 0.3rem"
              v-for="(param, index) in item.param"
              :key="index"
              >{{ param }}</el-tag
            >
            <div v-if="item.param.length <= 0">无参数</div>
          </el-card>
        </template>
      </el-table-column>
      <el-table-column
        prop="order_price_total"
        label="订单金额"
        align="center"
      ></el-table-column>
      <el-table-column label="状态" align="center">
        <template #default="scope">
          <el-tag
            style="font-size: 2rem; padding: 1rem"
            :type="scope.row.status ? 'success' : 'danger'"
            >{{ scope.row.status ? "已完成" : "进行中" }}</el-tag
          >
        </template>
      </el-table-column>
      <el-table-column label="类型" align="center">
        <template #default="scope">
          <el-tag
            style="font-size: 2rem; padding: 1rem"
            :type="scope.row.takeout_msg == null ? 'info' : ''"
            >{{ scope.row.takeout_msg == null ? "自取" : "外卖" }}</el-tag
          >
        </template>
      </el-table-column>
      <el-table-column label="用户备注" align="center">
        <template #default="scope">
          <span>{{
            scope.row.notes == null || scope.row.notes == ""
              ? "无"
              : scope.row.notes
          }}</span>
        </template>
      </el-table-column>
      <el-table-column
        prop="user_id"
        label="用户id"
        align="center"
      ></el-table-column>
      <el-table-column prop="create_time" label="下单时间" align="center">
        <template #default="scope">
          <div>{{ scope.row.create_time.slice(0, 10) }}</div>
          <div>{{ formatTime(scope.row.create_time) }}</div>
        </template>
      </el-table-column>
      <el-table-column label="操作" fixed="right" align="center">
        <template #default="scope">
          <el-tooltip
            effect="dark"
            placement="bottom"
            content="完成"
            v-if="!scope.row.status"
          >
            <el-button
              type="success"
              :icon="Check"
              circle
              @click="statusChange(scope.row)"
            />
          </el-tooltip>
          <el-tooltip effect="dark" placement="bottom" content="未完成" v-else>
            <el-button
              type="info"
              :icon="Close"
              circle
              @click="statusChange(scope.row)"
            />
          </el-tooltip>
          <el-tooltip effect="dark" placement="bottom" content="编辑">
            <el-button
              type="primary"
              :icon="Edit"
              circle
              @click="clickEditOrder(scope)"
            />
          </el-tooltip>
        </template>
      </el-table-column>
    </el-table>
    <!-- 分页 -->
    <el-pagination
      style="margin: 2rem auto; justify-content: center"
      background
      layout="prev, pager, next"
      :page-size="pageSize"
      @current-change="pageCurrentChange"
      :hide-on-single-page="orderTotal < pageSize ? true : false"
      :total="orderTotal"
    />
    <!-- 添加订单 -->
    <el-button
      id="addOrder"
      @click="
        getGoodsAndType();
        ShowStatus.addOrder = true;
      "
      >添加订单</el-button
    >
    <!-- 添加订单抽屉 -->
    <el-drawer v-model="ShowStatus.addOrder" direction="rtl">
      <template #title>
        <h3>添加订单</h3>
      </template>
      <template #default>
        <el-form
          ref="addOrderFormRef"
          :rules="formRuleAddOrder"
          :model="addOrderData"
          label-position="top"
        >
          <el-form-item label="订单内容">
            <div
              class="good"
              v-for="(good, goodIndex) in addOrderData.content"
              :key="goodIndex"
            >
              <div style="display: flex">
                <el-cascader
                  placeholder="请选择商品"
                  :show-all-levels="false"
                  :options="goodsAndTypeOptions"
                  :props="cascaderProps"
                  @change="addOrderGoodChang($event, goodIndex)"
                  v-model="good.cascaderValue"
                  style="flex: 1"
                />
                <div style="flex: 1; display: flex">
                  <span
                    style="margin-right: 0.5rem; flex: 1; text-align: center"
                    >数量</span
                  >
                  <el-input-number
                    style="flex: 4"
                    v-model="good.count"
                    :min="1"
                  />
                </div>
                <el-button
                  style="margin-left: 1rem"
                  :icon="Delete"
                  type="danger"
                  @click="addOrderData.content.splice(goodIndex, 1)"
                  circle
                />
              </div>
              <div
                v-for="(group, groupIndex) in good.value.param_data"
                :key="groupIndex"
              >
                <div>{{ group.group }}</div>
                <el-check-tag
                  style="margin: 1rem"
                  v-for="(param, index) in group.params"
                  :key="index"
                  :checked="group.choose == index"
                  @change="ParamTagChange(goodIndex, groupIndex, index)"
                  >{{ param }}</el-check-tag
                >
              </div>
              <el-divider border-style="dashed" />
            </div>
            <!-- value：商品数据 | count：商品数量 | cascaderValue：el-cascader的数据存放数组[null(类型数据),商品数据] -->
            <el-button
              @click="
                addOrderData.content.push({
                  value: { param_data: [] },
                  count: 1,
                  cascaderValue: [],
                })
              "
              >添加商品</el-button
            >
          </el-form-item>
          <el-form-item prop="status" label="订单状态">
            <span style="margin-right: 1rem">{{
              addOrderData.status == 1 ? "已完成" : "进行中"
            }}</span>
            <el-switch
              :before-change="addOrderStatusBeforeChange"
              v-model="addOrderData.status"
              :active-value="1"
              :inactive-value="0"
            />
          </el-form-item>
          <el-form-item label="订单类型">
            <span style="margin-right: 1rem">{{
              addOrderData.takeoutOrNot ? "外卖订单" : "自取订单"
            }}</span>
            <el-switch
              :before-change="editOrderTakeoutOrNotBeforeChange"
              v-model="addOrderData.takeoutOrNot"
            />
          </el-form-item>
          <el-form-item
            prop="takeout_msg.address"
            label="外卖地址"
            v-if="addOrderData.takeoutOrNot"
          >
            <el-input
              v-model="addOrderData.takeout_msg.address"
              type="textarea"
              placeholder="请输入外卖地址"
              :autosize="{ minRows: 1, maxRows: 4 }"
              clearable
            ></el-input>
          </el-form-item>
          <el-form-item
            prop="takeout_msg.phone"
            label="外卖电话"
            v-if="addOrderData.takeoutOrNot"
          >
            <el-input
              v-model="addOrderData.takeout_msg.phone"
              placeholder="请输入用户电话"
              style="text-align: center; width: 40%"
            ></el-input>
          </el-form-item>
          <el-form-item prop="user_id" label="用户id">
            <el-input
              v-model="addOrderData.user_id"
              disabled
              style="width: 30%"
            ></el-input>
          </el-form-item>
          <el-form-item prop="create_time" label="下单时间">
            <el-date-picker
              v-model="addOrderData.create_time"
              type="datetime"
              placeholder="请选择订单创建时间"
              :shortcuts="shortcutsCurrent"
            />
          </el-form-item>
          <el-form-item prop="finish_time" label="订单完成时间">
            <el-date-picker
              :disabled="addOrderData.status != 1"
              v-model="addOrderData.finish_time"
              type="datetime"
              placeholder="请选择订单完成时间"
              :shortcuts="shortcutsCurrent"
            />
          </el-form-item>
          <el-form-item prop="notes" label="订单备注(选填)">
            <el-input
              v-model="addOrderData.notes"
              type="textarea"
              placeholder="请输入订单备注"
              :autosize="{ minRows: 2, maxRows: 4 }"
              clearable
            ></el-input>
          </el-form-item>
        </el-form>
      </template>
      <template #footer>
        <div style="flex: auto">
          <el-button @click="ShowStatus.addOrder = false">取消</el-button>
          <el-button
            type="primary"
            @click="
              addOrder();
              ShowStatus.addOrder = false;
            "
            >提交</el-button
          >
        </div>
      </template>
    </el-drawer>
    <!-- 编辑订单对话框 -->
    <el-dialog v-model="ShowStatus.editOrder" title="编辑订单">
      <el-form
        ref="editOrderFormRef"
        :rules="formRuleEditOrder"
        :model="currentOrder"
        label-position="top"
      >
        <el-form-item label="订单id">
          <span style="margin-left: 2rem">{{
            JSON.parse(currentOrder.id)
          }}</span>
        </el-form-item>
        <el-form-item label="订单类型">
          <span style="margin-right: 1rem">{{
            currentOrder.takeoutOrNot ? "外卖订单" : "自取订单"
          }}</span>
          <el-switch
            :before-change="editOrderTakeoutOrNotBeforeChange"
            v-model="currentOrder.takeoutOrNot"
          />
        </el-form-item>
        <el-form-item
          prop="takeout_msg.address"
          label="外卖地址"
          v-if="currentOrder.takeoutOrNot"
        >
          <el-input
            v-model="currentOrder.takeout_msg.address"
            type="textarea"
            placeholder="请输入外卖地址"
            :autosize="{ minRows: 1, maxRows: 4 }"
            clearable
          ></el-input>
        </el-form-item>
        <el-form-item
          prop="takeout_msg.phone"
          label="外卖电话"
          v-if="currentOrder.takeoutOrNot"
        >
          <el-input
            v-model="currentOrder.takeout_msg.phone"
            placeholder="请输入用户电话"
            style="text-align: center; width: 40%"
          ></el-input>
        </el-form-item>
        <el-form-item label="订单内容">
          <div
            v-for="(good, editGoodIndex) in currentOrder.content"
            :key="editGoodIndex"
            style="width: 90%"
          >
            <div style="display: flex; flex-wrap: wrap">
              <el-cascader
                placeholder="请选择商品"
                :show-all-levels="false"
                :options="goodsAndTypeOptions"
                :props="cascaderProps"
                v-model="good.cascaderValue"
                @change="editGoodChange(good, $event)"
              />
              <div style="display: flex">
                <span style="margin-right: 0.5rem; flex: 1; text-align: center"
                  >数量</span
                >
                <el-input-number
                  style="flex: 4"
                  v-model="good.count"
                  :min="1"
                />
              </div>
              <el-button
                style="margin-left: 1rem"
                :icon="Delete"
                type="danger"
                @click="currentOrder.content.splice(editGoodIndex, 1)"
                circle
              />
            </div>
            <div
              v-for="goodData in good.goodData.param_data"
              :key="goodData.id"
            >
              <div>{{ goodData.group }}</div>
              <el-check-tag
                v-for="(param, paramIndex) in goodData.params"
                style="margin: 1rem"
                :checked="good.param.includes(param)"
                :key="paramIndex"
                @change="editOrderChange(good, goodData, param)"
                >{{ param }}</el-check-tag
              >
            </div>
            <el-divider border-style="dashed" />
          </div>
          <!-- value：商品数据 | count：商品数量 | cascaderValue：el-cascader的数据存放数组[null(类型数据),商品数据] == 1 ? '已完成' : '进行中'-->
          <el-button
            @click="
              currentOrder.content.push({
                goodData: { name: null },
                count: 1,
                cascaderValue: [],
                param: [],
              })
            "
            >添加商品</el-button
          >
        </el-form-item>
        <el-form-item label="订单总价">
          <el-input
            v-model="currentOrder.order_price_total"
            disabled
            style="text-align: center; width: 40%"
          ></el-input>
        </el-form-item>
        <el-form-item label="商品数量">
          <el-input
            v-model="currentOrder.product_count"
            disabled
            style="text-align: center; width: 40%"
          ></el-input>
        </el-form-item>
        <el-form-item label="订单状态">
          <span style="margin-right: 1rem">{{
            currentOrder.status == 1 ? "已完成" : "进行中"
          }}</span>
          <el-switch
            :active-value="1"
            :inactive-value="0"
            :before-change="editOrderStatusBeforeChange"
            v-model="currentOrder.status"
          />
        </el-form-item>
        <el-form-item prop="create_time" label="订单创建时间">
          <el-date-picker
            v-model="currentOrder.create_time"
            type="datetime"
            placeholder="请选择订单创建时间"
            :shortcuts="shortcutsCurrent"
          />
        </el-form-item>
        <el-form-item prop="finish_time" label="订单完成时间">
          <el-date-picker
            :disabled="currentOrder.status != 1"
            v-model="currentOrder.finish_time"
            type="datetime"
            placeholder="请选择订单完成时间"
            :shortcuts="shortcutsCurrent"
          />
        </el-form-item>
        <el-form-item prop="user_id" label="用户id">
          <el-input
            v-model="currentOrder.user_id"
            placeholder="请输入用户id"
            style="width: 30%"
            clearable
          ></el-input>
        </el-form-item>
        <el-form-item prop="notes" label="订单备注(选填)">
          <el-input
            v-model="currentOrder.notes"
            type="textarea"
            placeholder="请输入订单备注"
            :autosize="{ minRows: 2, maxRows: 4 }"
            clearable
          ></el-input>
        </el-form-item>
      </el-form>
      <template #footer>
        <span class="dialog-footer">
          <el-button @click="ShowStatus.editOrder = false">取消</el-button>
          <el-button @click="deleteOrder" type="danger">删除订单</el-button>
          <el-button
            type="primary"
            @click="
              submitEditOrder();
              ShowStatus.editOrder = false;
            "
            >提交</el-button
          >
        </span>
      </template>
    </el-dialog>
  </div>
</template>
<script setup>
import { Edit, Delete, Check, Close, Search } from "@element-plus/icons-vue";
import { ref, onMounted, reactive, getCurrentInstance, onUnmounted } from "vue";
import { initWebSocketHeartCheck } from "../utils/GeneralTool";
import { getData, currentDataChange, isJSON } from "../utils/GeneralTool"; // 导入全局工具
import { ElMessage, ElNotification, ElMessageBox } from "element-plus";
const { proxy } = getCurrentInstance();
// --数据获取--
let orderData = ref([]);
let searchOrNot = ref(false); // 是否搜索过
let orderTotal = ref(0);
let currentPage = ref(1); // 表格当前页
let pageSize = ref(10); // 表格页大小
const getOrderData = () => {
  // 获取订单数据，分页
  let params = [currentPage.value, pageSize.value];
  proxy.$api.getOrderData(params).then((res) => {
    getData(res.orderData, orderData);
    orderTotal.value = res.total;
  });
};
onMounted(() => {
  getOrderData(); // 获取订单数据
});
const pageCurrentChange = (val) => {
  // 翻页
  currentPage.value = val; // 更改当前页
  if (searchOrNot.value) {
    // 若筛选搜索过就调用筛选搜索方法
    search(false);
    return;
  }
  getOrderData();
};
const formatTime = (time) => {
  // 格式化时间函数
  let date = new Date(time);
  return date.getHours() + ":" + date.getMinutes() + ":" + date.getSeconds();
};

// --添加订单--
let ShowStatus = reactive({
  // 显示 / 隐藏 状态量
  addOrder: false,
  editOrder: false,
});
let goodsAndTypeOptions = ref([]); // 商品和商品类型的选项数据
let OptionsGetOrNot = false; // 是否请求商品和商品类型数据标志位
let getGoodsAndType = async () => {
  // 获取商品和商品类型数据
  if (!OptionsGetOrNot) {
    // 判断商品和商品类型是否已经获取
    await proxy.$api.getAllType().then((res) => {
      goodsAndTypeOptions = res;
    });
    for (let type of goodsAndTypeOptions) {
      type.label = type.name;
      let params = [type.id];
      await proxy.$api.getGoodsShortDataByType_id(params).then((res) => {
        for (let good of res) {
          good.label = good.name;
          good.value = {
            id: good.id,
            name: good.name,
            price: good.price,
            param_data: good.param_data,
            type_id: good.type_id,
          };
        }
        type.children = res;
      });
      if (type.children.length <= 0) type.disabled = true;
    }
    OptionsGetOrNot = true;
  }
  addOrderData.create_time = new Date(); // 将添加商品的时间设置为当前时间
};
const cascaderProps = {
  expandTrigger: "hover",
};
let addOrderFormRef = ref(); // 添加订单表单对象
let shortcutsCurrent = [
  {
    text: "现在",
    value: new Date(),
  },
  {
    text: "昨天",
    value: () => {
      const date = new Date();
      date.setTime(date.getTime() - 3600 * 1000 * 24);
      return date;
    },
  },
  {
    text: "一星期前",
    value: () => {
      const date = new Date();
      date.setTime(date.getTime() - 3600 * 1000 * 24 * 7);
      return date;
    },
  },
];
let addOrderData = reactive({
  // 添加订单的数据载体
  user_id: 1,
  status: 0,
  content: [],
  create_time: new Date(),
  takeoutOrNot: false, // 是否外卖
  takeout_msg: {
    address: null,
    phone: null
  },
}); // 数据载体
const finish_timeValidator = (rule, value, callback) => {
  // 自定义表单验证规则：订单完成时间规则
  if (addOrderData.status == 1) {
    if (value == "" || value == null) {
      callback(new Error("请选择订单完成时间"));
    }
  }
  callback();
};
const addOrderAddressValidator = (rule, value, callback) => {
  // 自定义表单验证规则：外卖地址规则
  if (addOrderData.takeout_msg != undefined) {
    if (value == "" || value == null) {
      callback(new Error("请输入外卖地址"));
    }
  }
  callback();
};
const addOrderPhoneValidator = (rule, value, callback) => {
  // 自定义表单验证规则：外卖地址规则
  if (addOrderData.takeout_msg != undefined) {
    if (value == "" || value == null) {
      callback(new Error("请输入外卖地址"));
    }
  }
  callback();
};
let formRuleAddOrder = reactive({
  // 添加订单的表单规则
  create_time: [
    { required: true, message: "请选择订单创建时间", trigger: "change" },
  ],
  finish_time: [{ validator: finish_timeValidator, trigger: "change" }],
  'takeout_msg.address': [
    { validator: addOrderAddressValidator, trigger: "blur" },
  ],
  'takeout_msg.phone': [
    { validator: addOrderPhoneValidator, trigger: "blur" },
  ],
});
const addOrderGoodChang = (typeAndGoodData, goodIndex) => {
  // 选择某商品的change事件
  addOrderData.content[goodIndex].value = JSON.parse(
    JSON.stringify(typeAndGoodData[1])
  ); // 赋值数据并分离vue监听
};
const ParamTagChange = (goodIndex, groupIndex, index) => {
  // 选择某商品的某参数的change事件
  addOrderData.content[goodIndex].value.param_data[groupIndex].choose = index;
};
let addOrderStatusBeforeChange = () => {
  // 是否完成按钮的change事件
  if (addOrderData.finish_time != null) {
    ElMessage({
      message: "请清空完成时间再改变订单状态",
      type: "error",
    });
    return false;
  }
  return true;
};
let addOrder = async () => {
  // 添加订单
  await addOrderFormRef.value.validate((valid) => {
    // 表单检验
    if (valid) {
      // 表单规则校验通过
      let content = []; // 数据库的content字段准备 [{id,param:[],count}]
      try {
        addOrderData.content.forEach((good) => {
          // 检查商品数据是否完善
          let goodData = { id: null, param: [], count: null }; // 商品载体
          if (good.value.id == null || good.value.id == "") {
            throw "请选择商品后再提交";
          }
          goodData.id = good.value.id;
          goodData.count = good.count;
          good.value.param_data.forEach((param) => {
            if (
              param.choose === null ||
              param.choose === "" ||
              param.choose === undefined
            ) {
              throw "请选择商品参数后再提交";
            }
            goodData.param.push(param.params[param.choose]);
          });
          content.push(goodData);
        });
      } catch (e) {
        ElNotification({
          title: "提交失败",
          message: e,
          type: "error",
        });
        return;
      }
      let data = { ...addOrderData };
      data.content = JSON.stringify(content);
      data.takeout_msg = JSON.stringify(data.takeout_msg)
      proxy.$api.addOrder(data).then((res) => {
        if (res.affectedRows > 0) {
          ElNotification({
            title: "添加成功",
            type: "success",
          });
        } else {
          ElNotification({
            title: "添加失败",
            type: "error",
          });
        }
      });
    } else {
      ElNotification({
        title: "提交失败，请完善订单信息",
        type: "error",
      });
    }
  });
};

// --编辑订单--
let currentOrder = reactive({ status: 0 }); // 当前订单载体
const editOrderFinish_timeValidator = (rule, value, callback) => {
  // 自定义表单验证规则：订单完成时间规则
  if (currentOrder.status == 1) {
    if (value == "" || value == null) {
      callback(new Error("请选择订单完成时间"));
    }
  }
  callback();
};
const editOrderAddressValidator = (rule, value, callback) => {
  // 自定义表单验证规则：外卖地址规则
  if (currentOrder.takeout_msg != undefined) {
    if (value == "" || value == null) {
      callback(new Error("请输入外卖地址"));
    }
  }
  callback();
};
const editOrderPhoneValidator = (rule, value, callback) => {
  // 自定义表单验证规则：用户电话规则
  if (currentOrder.takeout_msg != undefined) {
    if (value == "" || value == null) {
      callback(new Error("请输入电话号码"));
    }
    if (!/^1[3|4|5|6|7|8|9][0-9]{9}$/.test(value)) {
      callback(new Error("请输入正确的电话号码"));
    }
  }
  callback();
};
const formRuleEditOrder = reactive({
  // 编辑订单表单规则
  create_time: [
    { required: true, message: "请选择订单创建时间", trigger: "change" },
  ],
  finish_time: [
    { validator: editOrderFinish_timeValidator, trigger: "change" },
  ],
  "takeout_msg.address": [
    { validator: editOrderAddressValidator, trigger: "blur" },
  ],
  "takeout_msg.phone": [
    { validator: editOrderPhoneValidator, trigger: "blur" },
  ],
  user_id: [{ required: true, message: "请输入用户id", trigger: "blur" }],
});
const editOrderStatusBeforeChange = () => {
  // 编辑订单的商品状态改变的beforeChange事件
  if (currentOrder.finish_time != null) {
    ElMessage({
      message: "请清空完成时间再改变订单状态",
      type: "error",
    });
    return false;
  }
  return true;
};
const editOrderTakeoutOrNotBeforeChange = () => {
  // 编辑订单类型改变的beforeChange事件
  if (currentOrder.takeoutOrNot) {
    // 若原本为外卖订单就清空currentOrder.takeout_msg
    currentOrder.takeout_msg = undefined;
  } else {
    // 若原本为自取订单就添加currentOrder.takeout_msg的信息
    currentOrder.takeout_msg = {
      address: "",
      phone: "",
    };
  }
  return true;
};
const findOptionsValue = (id) => {
  // 在goodsAndTypeOptions中商品的value的工具函数(为了使用return 跳出两层循环)
  for (let typeOption of goodsAndTypeOptions) {
    for (let good of typeOption.children) {
      if (good.id == id) {
        return good.value;
      }
    }
  }
};
const clickEditOrder = async (scope) => {
  // 点击编辑订单事件
  await getGoodsAndType();
  currentDataChange(scope.row, currentOrder);
  currentOrder.takeoutOrNot = currentOrder.takeout_msg != undefined; // 判断是否为外卖订单，新增外卖状态量
  currentOrder.content.forEach((order) => {
    // JSON格式化 商品的参数
    if (isJSON(order.goodData.param_data)) {
      // 若可以转化为JSON数据
      order.goodData.param_data = JSON.parse(order.goodData.param_data); // 转化
    }
    order.cascaderValue = [undefined, findOptionsValue(order.goodData.id)]; // 货物信息初始化，el-cascader的展示
  });
  ShowStatus.editOrder = true;
};
const editOrderChange = (good, goodData, param) => {
  // 编辑订单内容的参数change事件
  good.param.forEach((originParam) => {
    // 清除原来的该类参数数据
    if (goodData.params.includes(originParam)) {
      good.param.splice(good.param.indexOf(originParam), 1);
    }
  });
  good.param.push(param);
};
const editGoodChange = (good, value) => {
  // 编辑商品的商品改变
  good.param = [];
  good.goodData = value[1];
};
const editOrderFormRef = ref();
const submitEditOrder = async () => {
  // 提交编辑的订单内容
  await editOrderFormRef.value.validate((valid) => {
    // 表单检验
    if (valid) {
      // 表单规则校验通过
      let content = []; // 数据库的content字段准备 [{id,param:[],count}]
      try {
        currentOrder.content.forEach((good) => {
          // 检查商品数据是否完善
          let goodData = { id: null, param: [], count: null }; // 商品载体
          if (good.goodData.id == null || good.goodData.id == "") {
            throw "请选择商品后再提交";
          }
          if (good.param.length <= 0 && good.goodData.param_data.length > 0) {
            throw "请完善商品参数后再提交";
          }
          goodData.id = good.goodData.id;
          goodData.count = good.count;
          goodData.param = [...good.param];
          content.push(goodData);
        });
      } catch (e) {
        ElNotification({
          title: "提交失败",
          message: e,
          type: "error",
        });
        return;
      }
      let data = { ...currentOrder };
      data.takeout_msg = JSON.stringify(data.takeout_msg);
      data.content = JSON.stringify(content);
      proxy.$api.updateOrder(data).then((res) => {
        if (res.affectedRows > 0) {
          ElNotification({
            title: "添加成功",
            type: "success",
          });
          getOrderData();
        } else {
          ElNotification({
            title: "添加失败",
            type: "error",
          });
        }
      });
    } else {
      ElNotification({
        title: "提交失败，请完善订单信息",
        type: "error",
      });
    }
  });
};
const statusChange = (data) => {
  // 订单状态改变事件
  let params = [data.id, data.status == 1 ? 0 : 1];
  proxy.$api.updateOrderStatus(params).then((res) => {
    if (res.affectedRows > 0) {
      ElNotification({
        title: "操作成功",
        type: "success",
      });
      getOrderData();
    } else {
      ElNotification({
        title: "操作失败",
        type: "error",
      });
    }
  });
};

// --删除--
const deleteOrder = () => {
  ElMessageBox.confirm("确定删除该订单吗？", {
    confirmButtonText: "确定",
    cancelButtonText: "取消",
  })
    .then(() => {
      let params = [currentOrder.id];
      proxy.$api.deleteOrder(params).then((res) => {
        if (res.affectedRows > 0) {
          ElNotification({
            title: "删除成功",
            type: "success",
          });
          getOrderData();
        } else {
          ElNotification({
            title: "操作失败",
            type: "error",
          });
        }
      });
    })
    .catch(() => {});
};

// --筛选搜索--
let searchData = reactive({
  status: false,
  takeoutOrNot: false,
}); // 筛选搜索数据载体
const cleanCondition = () => {
  // 清除筛选搜索条件
  searchData.status = false;
  searchData.takeoutOrNot = false;
  searchData.pickup_number = null;
  searchData.time = null;
};
const search = (buttonClickOrNot) => {
  // 筛选搜索
  if (buttonClickOrNot) {
    // 若是通过按钮点击搜索，重设当前页数和数据总量，进行搜索
    currentPage.value = 1;
    orderTotal.value = 0;
  }
  searchOrNot.value = true; // 修改搜索状态量，已经搜索过了
  let conditions = [
    searchData.pickup_number
      ? searchData.pickup_number.replace(/[b,B]/, "")
      : null,
    searchData.status,
    searchData.takeoutOrNot,
    searchData.time ? searchData.time : null,
    currentPage.value,
    pageSize.value,
  ];
  proxy.$api.searchOrderByCondition(conditions).then((res) => {
    getData(res.orderData, orderData);
    orderTotal.value = res.total;
  });
};

// --WebSocket监控订单更新状态--
let ws = null;
let pageDestruction = false; // 页面销毁状态量
const WebSocketHeartCheck = initWebSocketHeartCheck(); // 初始化websocket心跳检测
const connectWebSocketWatchOrder = () => {
  // 连接WebSocket监控订单情况函数
  ws = new WebSocket("ws://localhost:3000/order/socket/watchOrder");
  ws.onopen = () => {
    WebSocketHeartCheck.startHeartCheck(ws); // 启动websocket心跳检测
  };
  ws.onmessage = (event) => {
    WebSocketHeartCheck.startHeartCheck(ws); // 启动websocket心跳检测
    let data = event.data === "pong" ? event.data : JSON.parse(event.data);
    // console.log("收到的消息：", data);
    if (data.type === "updateOrder") {
      getOrderData(); // 重新获订单数据
    } else if (data.type === "newOrder") {
      getOrderData(); // 重新获订单数据
      ElNotification({
        title: "您有新的订单啦",
        type: "success",
      });
    }
  };
  ws.onclose = () => {
    WebSocketHeartCheck.resetHeartCheck(); // 重置websocket心跳检测
    if (!pageDestruction) connectWebSocketWatchOrder(); // 若页面未被销毁，重新连接
  };
  ws.onerror = (error) => {
    WebSocketHeartCheck.resetHeartCheck(); // 重置websocket心跳检测
    ElNotification({
      title: "网络连接出现错误",
      message: error,
      type: "error",
    });
  };
};
connectWebSocketWatchOrder(); // 连接WebSocket监控订单情况

onUnmounted(() => {
  pageDestruction = true; // 页面销毁
  ws.close(); // 关闭websocket连接
});
</script>

<style lang="scss" scoped>
#orderPage {
  padding: 20px 0;
}
#topBar {
  width: 80%;
  margin: 0 auto;
  display: flex;
  align-items: center;
  justify-content: center;
  margin-bottom: 2rem;

  .topBarSwitch {
    margin-right: 1rem;
    font-size: 2rem;
    font-weight: 400;

    span {
      margin-right: 1rem;
      font-size: 2rem;
      font-weight: 400;
    }
  }
}

#addOrder {
  margin: 0 auto;
  display: block;
  margin-top: 2rem;
  width: 50%;
  height: 5rem;
  font-size: 3rem;
}

h3 {
  font-size: 2rem;
}

.good {
  display: block;
  width: 100%;
}
</style>
<style scoped>
/deep/.el-card__header {
  padding: 0;
}

.card-header {
  display: flex;
  justify-content: space-between;
  align-items: center;
  padding: 0.5rem;
}

/deep/.el-card {
  margin-bottom: 1rem;
}

::v-deep .el-table--scrollable-y .el-table__body-wrapper {
  overflow-y: hidden;
}

/deep/ .el-date-editor .el-range-separator {
  color: rgba(24, 24, 24, 0.6);
}
</style>>